package electronics.application;

import java.io.*;
import java.util.*;
import electronics.base.*;

/**
/*
/*将read两个方法的参数列表改为words:String 
/*部分方法访问权限改为private
/*
 * TODO run()待补充。缺失的方法见类图
 * 修改了getChoice(int limit),limit为选项数字上限（这样可以用于其他选项使用）
 *
 */

public class ElectronicsManage {
	private Vector<Computer> computers=new Vector<Computer>();//Vector未初始化时add函数一直报错，所以将 computers初始化
	private Vector<Phone> phones=new Vector<Phone>();
	
	private File file_computer;
	private File file_phone;
	
	private static BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
	
	public static void main(String[] args) throws IOException {
		Application elect = new Application();
		elect.begin();
		elect.run();
		
	}
	
	
	
	/**
	 * 初始化系统，将文件中原有数据加载进程序的vector类中
	 * 
	 */
	private void begin() {
		String path = System.getProperty("user.dir");
		String s = null;
		file_computer = new File(path+"/computer_information.txt");
		file_phone = new File(path+"/phone_information.txt");
		if(file_computer.exists()&&file_phone.exists()) {
			try {
				BufferedReader br1 =new BufferedReader(new InputStreamReader(new FileInputStream(file_computer),"UTF-8") );
				//换成了new InputStreamReader(new FileInputStream(file_computer),"UTF-8")，因为txt文件中用到了汉语，不做编码转化的话会出现乱码
				BufferedReader br2 =new BufferedReader(new InputStreamReader(new FileInputStream(file_phone),"UTF-8") );
				while ((s = br2.readLine()) != null ) {
						addPhone(readPhone(s));
				}
				while ((s = br1.readLine()) != null ) {
						addComputer(readComputer(s));			
				}
				
			} catch (IOException e) {
				e.getStackTrace();
			}
		}
		else {
			throw new NullPointerException("\n can't find the file");
		}
	}
	
	
	
	/**
	 * TODO 选项待补充
	 * @throws IOException
	 */
	public void run() throws IOException {
		while(true) {
			System.out.println("\n[0] Quit\n"+
							   "[1] Add a computer\n"+
							   "[2] Add a phone\n"+
							   "[3] Show all computers\n"+
							   "[4] Show all phones\n"+
							   "[5] Set attributes of electronics\n"+
							   "[6] Show the number of electronics\n"+
							   "[7] Judge if the specific electronic exists\n"+
							   "Please input your choice: ");
			int choice = getChoice(8);
			if (choice == 1) {
				System.out.println("Please input the information of the new computer:");
				System.out.println("(weight_price_powerConsumption_producer_CPU_RAM)");
				
				//让用户输入新电脑的信息
				String info = null;
				info = stdIn.readLine();
			
				//读取新电脑的信息并且实例为一个新的Computer对象添加到computers中
				if( readComputer(info) != null ) {
					addComputer(readComputer(info));
					System.out.println("Creation complete");
				} else {
					System.out.println("Invalid input! failed to create");
				}
			}
			else if (choice == 2) {
				System.out.println("Please input the information of the new phone:");
				System.out.println("(weight_price_powerConsumption_producer_system_memory)");
				
				//让用户输入新手机的信息
				BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
				String info = null;
				info = br.readLine();
				
				//读取新手机的信息并实例为一个新的Phone对象添加到phones中
				if( readPhone(info) != null ) {
					addPhone(readPhone(info));
					System.out.println("Creation complete");
				} else {
					System.out.println("Invalid input! failed to create");
				}
			}
			else if (choice == 3) {
				System.out.println("weight_price_powerConsumption_producer_CPU_RAM");
				System.out.println(toStringComputer());
			}
			else if (choice == 4) {
				System.out.println("weight_price_powerConsumption_producer_system_memory");
				System.out.println(toStringPhone());
			}
			else if (choice == 5) {
				set();
			}
			else if (choice == 6) {
				System.out.println("computers:"	+ getNumberOfComputers());
				System.out.println("phones:"	+ getNumberOfPhones());
			}
			else if (choice == 7) {
				System.out.println("Please input the type of the electronics[phone/computer]:");
				//让用户输入需要查找的type
				try {
					
					String t = stdIn.readLine();
					if(t.equals("computer")) {
                        System.out.println("(weight_price_powerConsumption_producer_CPU_RAM)");
						//让用户输入新电脑的信息 
						String info = null;
						info = stdIn.readLine();
						boolean is =ComputerIsExist(readComputer(info));
						if(is) {
							System.out.println("Is found:"+info);
						}
						else {
							System.out.println("Is not found:"+info);
						}
					}
					else if(t.equals("phone")) {
						System.out.println("(weight_price_powerConsumption_producer_system_memory)");
						
						//让用户输入新手机的信息
						String info = null;
						info = stdIn.readLine();
						boolean is =PhoneIsExist(readPhone(info));
						if(is) {
							System.out.print("\nIs found:"+info);
						}
						else {
							System.out.print("\nIs not found:"+info);
						}
					}
				}
				catch(IOException e) {
					e.getStackTrace();
				}	

			}
			else {
				saveInfoOfComputer();
				saveInfoOfPhone();
				break;
			}
		}
		
	}

	/**
	 * 用于获取用户输入的选项
	 * @param limit 选项数字大小限于0~limit之间
	 * @return 用户输入的选项
	 * @throws IOException
	 */
	public int getChoice(int limit) throws IOException {
		int number;
		
		while(true) {
			
			try {
				number = Integer.parseInt(stdIn.readLine());
				
				if(number >=0 && number <= limit) {
					return number;
				}
				else {
					System.out.println("\nInvalid input!! Please try again: ");
				}
				
			} catch (NumberFormatException e) {
				System.out.print(e);
			}
		}
	}
	
	/**
	 * 根据字符串"weight_price_powerConsumption_producer_CPU_RAM"读取信息，创建Computer对象
	 * @param words 固定格式的字符串
	 * @return 获取信息后实例化的computer对象
	 */
	
	public Computer readComputer(String words) {
		final String DELIM = "_";
		double weight = 0;
		double price = 0;
		int powerConsumption = 0;
		String producer = null, CPU = null, RAM = null;
		
		StringTokenizer tokenizer = new StringTokenizer(words, DELIM);
		if (tokenizer.countTokens() != 6) {
			System.out.println("\nInvalid input!! Please try again: ");
		} 
		else {
			   try {
				weight = Double.parseDouble(tokenizer.nextToken());
				price = Double.parseDouble(tokenizer.nextToken());
				powerConsumption = Integer.parseInt(tokenizer.nextToken());
				producer = tokenizer.nextToken();
				CPU = tokenizer.nextToken();
				RAM = tokenizer.nextToken();
				
				if(weight<=0 || price<0 || powerConsumption<0) {
					System.out.println("\nInvalid input!! Please try again: ");
				    }
		     
			} catch (NumberFormatException e) {
				System.out.println(e);
		
			}
		}
		return new Computer(weight,price,powerConsumption,producer,CPU,RAM);
		
	}
	
	/**
	 * 根据字符串"weight_price_powerConsumption_producer_system_memory"读取信息，创建Phone对象
	 * @param words 固定格式的字符串
	 * @return 根据信息创建的Phone对象
	 */
	public Phone readPhone(String words) {
		final String DELIM = "_";
		double weight=0;
		double price=0;
		int powerConsumption=0;
		String producer=null, system=null, memory=null;
		
		StringTokenizer tokenizer = new StringTokenizer(words, DELIM);
		if (tokenizer.countTokens() != 6) {
			System.out.println("\nInvalid input!! Please try again: ");
		} 
		else {
			   try {
				weight = Double.parseDouble(tokenizer.nextToken());
				price = Double.parseDouble(tokenizer.nextToken());
				powerConsumption = Integer.parseInt(tokenizer.nextToken());
				producer = tokenizer.nextToken();
				system = tokenizer.nextToken();
				memory = tokenizer.nextToken();
				
				if(weight<=0 || price<0 || powerConsumption<0) {
					System.out.println("\nInvalid input!! Please try again: ");
				    }
		     
			} catch (NumberFormatException e) {
				System.out.println(e);
		
			}
		}
		return new Phone(weight,price,powerConsumption,producer,system,memory);
	}
	
	/**
	 * 将Computer对象添加进<code>computers</code>中
	 * @param newcomputer 要添加的Computer对象
	 */
	private void addComputer(Computer newcomputer) {
		if(newcomputer != null) {
			computers.add(newcomputer);
		}
		else {
			throw new NullPointerException("Cannot invoke java.util.Vector.add(Object) because this.computers is null");
		}
	}
	
	/**
	 * 将Phone对象添加进<code>phones</code>中
	 * @param newphone 要添加的Phone对象
	 */
	private void addPhone(Phone newphone) {
		if(newphone !=null) {
			phones.add(newphone);
		}
		else {
			throw new NullPointerException("Cannot invoke java.util.Vector.add(Object) because this.computers is null");
		}
		
	}
	
	/**
	 * 获取特定序号的Computer对象
	 * @param index 用户输入的序号
	 * @return 序号对应的对象
	 */
	private Computer getComputer(int index) {
		return computers.get(index);
	}
	
	/**
	 * 获取特定序号的Phone对象
	 * @param index 用户输入的序号
	 * @return 序号对应的对象
	 */
	public Phone getPhone(int index) {
		return phones.get(index);
	}
	/**
	 * get the specific electronic object like: computer/phone 
	 * Obtains the number inputed by users 
	 * Use the number to find the object(computer/phone)
	 */
	public void getSpecificElectronic() {
		
		System.out.println(" Please iuput the type of the electronic [computer/phone]");
		try {
			String type = stdIn.readLine();
			if(type.equals("computer")) {
				System.out.println("computer :the range of number is 0-"+computers.size());
				int index = getChoice(getNumberOfComputers());
				getComputer(index).showInfo();;
			}
			else if(type.equals("phone")) {
				System.out.println("phone :the range of number is 0-"+phones.size());
				int index = getChoice(getNumberOfPhones());
				getPhone(index).showInfo();;
			}
		}
		catch(IOException e){
			e.getStackTrace();
		}
	}

	/**
	 * 遍历数组computers中的元素
	 * 返回所有元素所有成员变量的值（String）
	 */
	public String toStringComputer() {
		String temp = "";
		for (Computer C : computers) {
            //再每一个对象间隔加了"_"符号，方便直接输入txt中
    		temp += C.getWeight() +"_"+ C.getPrice() +"_"+ C.getPowerConsumption() +"_"+ C.getProducer() +"_"+ C.getCPUversion() +"_"+ C.getRAM()  + "\n";
    	}
    	return temp;
	}
	
	/**
	 * 遍历数组phones中的元素
	 * 返回所有元素所有成员变量的值（String）
	 */
	public String toStringPhone() {
		String temp = "";
		for (Phone P : phones) {
            //再每一个对象间隔加了"_"符号，方便直接输入txt中
    		temp += P.getWeight() +"_"+ P.getPrice() +"_"+ P.getPowerConsumption() +"_"+ P.getProducer() +"_"+ P.getSystem() +"_"+ P.getMemory()+ "\n";
    	}
    	return temp;
	}
    	
	/**
	 * 遍历数组computers和phones中的元素
	 * 返回所有元素所有成员变量的值（String）
	 */
	public String toStringAll() {
		String temp = "\n";
		temp = "Computers:\n" + toStringComputer() + "Phones:\n" + toStringPhone();
		return temp;
	}
	
	/**
	 * 返回数组computers中元素的个数
	 */
	private int getNumberOfComputers() {
		return computers.size();
	}
	
	/**
	 * 返回数组phones中元素的个数
	 */
	private int getNumberOfPhones() {
		return phones.size();
	}
	
	/**
	 * 判断该computer是否存在
	 */
	private boolean ComputerIsExist(Computer C) {
		boolean exist=false;
		for(Computer find:computers) {
			if(find.equalComputer(C)) {
				exist=true;
			}
		}
		return exist;
	}
	
	/**
	 * 判断该phone是否存在
	 */
	private boolean PhoneIsExist(Phone P) {
		boolean exist=false;
		for(Phone find:phones) {
			if(find.equalPhone(P)) {
				exist=true;
			}
		}
		return exist;
	}


	/**
	 * 重新设置electronic中对象的属性
	 */
	public void set() {
		System.out.println(" Please iuput the type of the electronic [computer/phone]");
		try {
			String type = stdIn.readLine();
		 if(type.equals("computer")) {
		    System.out.println("computer :the range of number is 0-"+computers.size());
			int index = getChoice(getNumberOfComputers());
			
            System.out.println("(weight_price_powerConsumption_producer_CPU_RAM)");
            String setNew= stdIn.readLine(); 
            Computer aNew =readComputer(setNew);
            computers.set(index, aNew);
            System.out.println("output the modified information");
            getComputer(index).showInfo();
   
		 }
		 else if(type.equals("phone")) {
			 System.out.println("computer :the range of number is 0-"+computers.size());
			int index = getChoice(getNumberOfComputers());        
			System.out.println("(weight_price_powerConsumption_producer_system_memory)");
	        String setNew= stdIn.readLine(); 
	        Phone aNew =readPhone(setNew);
	        phones.set(index, aNew);
            System.out.println("output the modified information");
            getPhone(index).showInfo();
			
		 }
	}catch(IOException e) {
		e.getStackTrace();
	}	
		
	}
	/**
	 * 将computers所有的信息存贮近computer_information.txt中
	 */
	private void saveInfoOfComputer() {
		if(file_computer.exists()) {

			try {
				PrintWriter Store = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file_computer), "UTF-8"));
				Store.print(toStringComputer());
				Store.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   }
	}
	/**
	 * 将phones所有的信息存贮进phone_information.txt中
	 */
	private void saveInfoOfPhone() {
		
		if(file_phone.exists()) {

			try {
                //利用了OutputStreamWriter可以将字节流重新以新的方式编码，防止出现非认知内的汉字（乱码）
				PrintWriter Store = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file_phone), "UTF-8"));
				Store.print(toStringPhone());
				Store.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	   }
	
	}
}

	
	
	
	
	